package com.ruoyi.user.controller;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.user.domain.ReviewReply;
import com.ruoyi.user.domain.UserOrderReview;
import com.ruoyi.user.service.IReviewReplyService;
import com.ruoyi.user.domain.vo.OrderReviewDetailVO;
import com.ruoyi.user.service.IUserOrderReviewsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * 用户订单评价与回复接口
 */
@RestController
@RequestMapping("/user/reviews")
public class UserOrderReviewsController extends BaseController {

    @Resource
    private IUserOrderReviewsService userOrderReviewsService;

    @Resource
    private IReviewReplyService reviewReplyService;

    /**
     * 按商家ID分页查询评价列表
     */
    @PreAuthorize("@ss.hasPermi('user:reviews:list')")
    @GetMapping("/listByMerchant")
    public TableDataInfo listByMerchant(@RequestParam("merchantId") Long merchantId) {
        startPage();
        List<OrderReviewDetailVO> list = userOrderReviewsService.selectOrderReviewDetailsByMerchantId(merchantId);
        return getDataTable(list);
    }

    /**
     * 按订单ID分页查询评价详情列表
     */
    @PreAuthorize("@ss.hasPermi('user:reviews:list')")
    @GetMapping("/listByOrder")
    public TableDataInfo listByOrder(@RequestParam("orderId") Long orderId) {
        startPage();
        List<OrderReviewDetailVO> list = userOrderReviewsService.selectOrderReviewDetailsByOrderId(orderId);
        return getDataTable(list);
    }

    /**
     * 根据评价ID获取详情
     */
    @PreAuthorize("@ss.hasPermi('user:reviews:query')")
    @GetMapping("/{reviewId}")
    public AjaxResult getReview(@PathVariable("reviewId") Long reviewId) {
        OrderReviewDetailVO detail = userOrderReviewsService.selectOrderReviewDetailById(reviewId);
        return AjaxResult.success(detail);
    }

    /**
     * 获取评价的回复列表
     */
    @PreAuthorize("@ss.hasPermi('user:reviews:reply:list')")
    @GetMapping("/{reviewId}/replies")
    public TableDataInfo getReplies(@PathVariable("reviewId") Long reviewId) {
        startPage();
        List<ReviewReply> replies = reviewReplyService.selectRepliesByReviewId(reviewId);
        return getDataTable(replies);
    }

    /**
     * 对某评价进行回复（商家或平台客服）
     */
    @PreAuthorize("@ss.hasPermi('user:reviews:reply:add')")
    @Log(title = "评价回复", businessType = BusinessType.INSERT)
    @PostMapping("/{reviewId}/reply")
    public AjaxResult reply(@PathVariable("reviewId") Long reviewId,
                            @RequestBody ReviewReply body) {
        if (body == null || StringUtils.isEmpty(body.getReplyContent())) {
            return AjaxResult.error("回复内容不能为空");
        }
        body.setReviewId(reviewId);
        if (body.getReplierId() == null) {
            Long loginUserId = SecurityUtils.getUserId();
            body.setReplierId(loginUserId);
        }
        if (body.getStatus() == null) {
            body.setStatus(1);
        }
        int rows = reviewReplyService.insertReply(body);
        return toAjax(rows);
    }

    /**
     * 新增订单评价（用户或商家二选一，互斥）
     */
    @PreAuthorize("@ss.hasPermi('user:reviews:add')")
    @Log(title = "订单评价", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody UserOrderReview review) {
        if (review == null) {
            return AjaxResult.error("请求体不能为空");
        }
        if (review.getOrderId() == null) {
            return AjaxResult.error("orderId不能为空");
        }
        boolean hasCustomer = review.getCustomerId() != null;
        boolean hasMerchant = review.getMerchantId() != null;
        if (hasCustomer == hasMerchant) {
            return AjaxResult.error("customerId与merchantId必须二选一且仅填一个");
        }
        if (review.getScore() == null) {
            return AjaxResult.error("score不能为空");
        }
        int rows = userOrderReviewsService.insertOrderReview(review);
        return toAjax(rows);
    }
}
